<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>登录页面</title>
  <!-- 引入外部CSS样式 -->
  <link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/static/css/login.css">
  <!-- 引入jQuery -->
  <script src="static/js/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="login-container">
  <div class="login-form">
    <h2>用户登录</h2>
    <form id="loginForm">
      <div class="form-group">
        <label for="username">用户名</label>
        <input type="text" id="username" name="username" required>
      </div>
      <div class="form-group">
        <label for="password">密码</label>
        <input type="password" id="password" name="password" required>
      </div>
      <button type="submit" class="login-btn">登录</button>
      <p id="errorMessage" class="error-message"></p>
    </form>
  </div>
</div>

<script>
  $(document).ready(function() {
    $("#loginForm").submit(function(event) {
      event.preventDefault();  // 阻止表单的默认提交行为

      // 获取用户名和密码
      var username = $("#username").val();
      var password = $("#password").val();

      // 使用AJAX发送登录请求
      $.ajax({
        url: "/user/login",  // 目标URL
        type: "POST",  // 请求类型
        data: {
          username: username,
          password: password
        },
        dataType: "json",  // 返回数据格式
        success: function(response) {
          console.log(response)
          if (response.code === 200) {
            // 登录成功
            // 登录成功，跳转到服务器端控制的隐藏页面
            const userInfo = response.data;
            if(userInfo['userType']==='student'){
              window.location.href = "/student/home";  // 跳转到服务器端控制的页面
            }else{
              window.location.href = "/teacher/home";  // 跳转到服务器端控制的页面
            }

          } else {
            // 登录失败，显示错误信息
            alert('登录失败')
            $("#errorMessage").text(response.msg);
          }
        },
        error: function(xhr, status, error) {
          // 请求失败时的错误处理
          $("#errorMessage").text("请求失败，请重试！");
        }
      });
    });
  });
</script>

</body>
</html>
